package com.laf.manage.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.google.zxing.client.result.BizcardResultParser;
import com.laf.common.constant.MQConstant;
import com.laf.common.exception.ServiceException;
import com.laf.manage.domain.doc.ReceiveRecordDoc;
import com.laf.manage.domain.po.ReceiveRecord;
import com.laf.manage.mapper.es.ReceiveRecordEsMapper;
import com.laf.manage.service.IReceiveRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ReceiveRecordListener {

    private final IReceiveRecordService receiveRecordService;

    private final ReceiveRecordEsMapper receiveRecordEsMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = MQConstant.LOST_ITEM_RECORD_QUEUE,
                    durable = "true",
                    arguments = @Argument(name = "x-queue-mode", value = "lazy")

            ),
            exchange = @Exchange(MQConstant.RECEIVE_RECORD_EXCHANGE),
            key = MQConstant.LOST_ITEM_RECORD_ROUTING_KEY
    ))
    public void addReceiveRecordToEs(Long id) {
        // 校验数据
        ReceiveRecord receiveRecord = receiveRecordService.getById(id);
        if (receiveRecord == null) return;

        // 幂等性处理
        ReceiveRecordDoc recordDoc = receiveRecordEsMapper.selectById(id);
        if (recordDoc != null) return;

        // po 转换为 doc
        ReceiveRecordDoc insertDoc = BeanUtil.copyProperties(receiveRecord, ReceiveRecordDoc.class);
        if (CollUtil.isNotEmpty(receiveRecord.getItemUrls())) {
            insertDoc.setItemUrl(receiveRecord.getItemUrls().get(0));
        }

        // 写入 es
        Integer result = receiveRecordEsMapper.insert(insertDoc);
        if (result <= 0) throw new ServiceException("写入 es 失败");

    }

}
